# -*- coding: utf-8 -*-
from django.shortcuts import render
from .models import *
from . import run_thead
from ratelimit.decorators import ratelimit
import json
import datetime
import random

# Create your views here.
# start main,but is in python3 manage.py runserver 0.0.0.0:*的情况下才能生效，后期修复
run_thead.run()

def index(requests):
    return render(requests, "lottery/index.html")

@ratelimit(key='ip', rate='1000/1h', block=True)
def open_data(requests):
    today = datetime.date.today()
    contacts = []
    last_ssq = Open_history.objects.filter(lottery_id=1).last()
    contact = {}
    contact['id'] = last_ssq.id
    date_open_list = [1,3,6]
    if today.weekday() in date_open_list:
        contact['open'] = True
    contact['logo'] = "【福彩】双色球"
    contact['code'] = last_ssq.code
    contact['date'] = last_ssq.open_date
    contact['red_list'] = json.loads(last_ssq.red_list)
    contact['blue_list'] = json.loads(last_ssq.blue_list)
    contacts.append(contact)

    last_fc3d = Open_history.objects.filter(lottery_id=3).last()
    contact = {}
    contact['id'] = last_fc3d.id
    contact['open'] = True
    contact['logo'] = "【福彩】3D"
    contact['code'] = last_fc3d.code
    contact['date'] = last_fc3d.open_date
    contact['red_list'] = json.loads(last_fc3d.red_list)
    contacts.append(contact)

    last_qilecai = Open_history.objects.filter(lottery_id=7).last()
    contact = {}
    contact['id'] = last_qilecai.id
    date_open_list = [0,2,4]
    if today.weekday() in date_open_list:
        contact['open'] = True
    contact['logo'] = "【福彩】七乐彩"
    contact['code'] = last_qilecai.code
    contact['date'] = last_qilecai.open_date
    contact['red_list'] = json.loads(last_qilecai.red_list)
    contact['blue_list'] = json.loads(last_qilecai.blue_list)
    contacts.append(contact)

    last_dlt = Open_history.objects.filter(lottery_id=2).last()
    contact = {}
    contact['id'] = last_dlt.id
    date_open_list = [0,2,5]
    if today.weekday() in date_open_list:
        contact['open'] = True
    contact['logo'] = "【体彩】大乐透"
    contact['code'] = last_dlt.code
    contact['date'] = last_dlt.open_date
    contact['orange_list'] = json.loads(last_dlt.orange_list)
    contact['solida_list'] = json.loads(last_dlt.solida_list)
    contacts.append(contact)

    last_qixincai = Open_history.objects.filter(lottery_id=4).last()
    contact = {}
    contact['id'] = last_qixincai.id
    date_open_list = [1,4,6]
    if today.weekday() in date_open_list:
        contact['open'] = True
    contact['logo'] = "【体彩】七星彩"
    contact['code'] = last_qixincai.code
    contact['date'] = last_qixincai.open_date
    contact['red_list'] = json.loads(last_qixincai.red_list)
    contacts.append(contact)

    last_pl3 = Open_history.objects.filter(lottery_id=5).last()
    contact = {}
    contact['id'] = last_pl3.id
    contact['logo'] = "【体彩】排列3"
    contact['open'] = True
    contact['code'] = last_pl3.code
    contact['date'] = last_pl3.open_date
    contact['red_list'] = json.loads(last_pl3.red_list)
    contacts.append(contact)

    last_pl5 = Open_history.objects.filter(lottery_id=6).last()
    contact = {}
    contact['id'] = last_pl5.id
    contact['logo'] = "【体彩】排列5"
    contact['open'] = True
    contact['code'] = last_pl5.code
    contact['date'] = last_pl5.open_date
    contact['red_list'] = json.loads(last_pl5.red_list)
    contacts.append(contact)

    return render(requests, "lottery/open_data.html",{"title_info":"彩票开奖","contacts":contacts})


def will(requests):
    l_id = requests.GET.get('id')
    lo = Open_history.objects.get(pk=l_id)
    title_info = lo.lottery_name + "算法预测"
    today = datetime.date.today()
    w = today.weekday()
    if lo.lottery_id in [3,5,6]:
        date = "今晚开奖"
    elif lo.lottery_id in [1]:
        if w in [0,2,5]:
            date = "明晚开奖"
        elif w in [1,3,6]:
            date = "今晚开奖"
        else:
            date = "后天开奖"
    elif lo.lottery_id in [2]:
        if w in [6,1,4]:
            date = "明晚开奖"
        elif w in [0,2,5]:
            date = "今晚开奖"
        else:
            date = "后天开奖"
    elif lo.lottery_id in [4]:
        if w in [0,3,5]:
            date = "明晚开奖"
        elif w in [1,4,6]:
            date = "今晚开奖"
        else:
            date = "后天开奖"
    elif lo.lottery_id in [7]:
        if w in [6,1,3]:
            date = "明晚开奖"
        elif w in [0,2,4]:
            date = "今晚开奖"
        else:
            date = "后天开奖"
    link_data = Alg_everyone.objects.filter(link_id=int(l_id))
    contacts = []
    contacts2 = {"l_id":lo.id,
                "link__code":lo.code+1,
                "logo": "【{a}】{b}".format(a=lo.lottery_publisher, b=lo.lottery_name),
                "date":date}
    num = 0
    for d in link_data:
        alg_data = json.loads(d.alg_data)
        contact = {'l_id':l_id,
                    "num":num+1,
                    "a_id":d.id,
                    "link__code":lo.code+1,
                    "alg_name":d.alg_name,
                    "link_id__lottery_id":lo.lottery_id
                    }
        num += 1
        if lo.lottery_id in [2,]:
            contact['orange'] = alg_data['will']['orange']
            contact['solida'] = alg_data['will']['solida']
            contact['kill_orange'] = alg_data['kill']['orange']
            contact['kill_solida'] = alg_data['kill']['solida']
        elif lo.lottery_id in [3,4,5,6]:
            contact['red'] = alg_data['will']['red']
            contact['kill_red'] = alg_data['kill']['red']
        elif lo.lottery_id in [1,7]:
            contact['red'] = alg_data['will']['red']
            contact['blue'] = alg_data['will']['blue']
            contact['kill_red'] = alg_data['kill']['red']
            contact['kill_blue'] = alg_data['kill']['blue']
        contacts.append(contact)

    return render(requests, "lottery/will.html",{"title_info":title_info,
                    "contacts":contacts,"contacts2":contacts2})


def old(requests):
    l_id = requests.GET.get('id')
    lo = Open_history.objects.get(pk=int(l_id))
    title_info = lo.lottery_name + "预测结果"

    # 获取上一期的code
    # 上期的绑定的算法数据是期的开奖号码
    code_pre = Open_history.objects.filter(lottery_id=lo.lottery_id,code=lo.code-1)
    if not code_pre:
        return render(requests, "lottery/old.html",{"title_info":title_info})

    # 上期预测数据
    f = Alg_everyone.objects.filter(link_id=code_pre[0].id)
    contacts = []
    for g in f:
        alg_data = json.loads(g.alg_data)
        contact = {'alg_name':g.alg_name}
        if lo.lottery_id in [2,]:
            contact['orange'] = alg_data['will']['orange']
            contact['solida'] = alg_data['will']['solida']
        elif lo.lottery_id in [3,4,5,6]:
            contact['red'] = alg_data['will']['red']
        elif lo.lottery_id in [1,7]:
            contact['red'] = alg_data['will']['red']
            contact['blue'] = alg_data['will']['blue']
        contacts.append(contact)
    # 这期开奖数据
    open_data = {}
    if lo.lottery_id in [2,]:
        open_data['orange'] = json.loads(lo.orange_list)
        open_data['solida'] = json.loads(lo.solida_list)
    elif lo.lottery_id in [3,4,5,6]:
        open_data['red'] = json.loads(lo.red_list)
    elif lo.lottery_id in [1,7]:
        open_data['red'] = json.loads(lo.red_list)
        open_data['blue'] = json.loads(lo.blue_list)

    result_data = []
    num = 0
    for c in contacts:
        num += 1
        result = {}
        result['num'] = num
        result['right_orange'] = []
        result['right_solida'] = []
        result['right_red'] = []
        result['right_blue'] = []
        if lo.lottery_id in [2,]:
            for o in open_data['orange']:
                if o in c['orange']:
                    result['right_orange'].append(o)
            for o in open_data['solida']:
                if o in c['solida']:
                    result['right_solida'].append(o)
        elif lo.lottery_id in [3,4,5,6]:
            for o in open_data["red"]:
                if o in c['red']:
                    result['right_red'].append(o)
        elif lo.lottery_id in [1,7]:
            for o in open_data['red']:
                if o in c['red']:
                    result['right_red'].append(o)
            for o in open_data['blue']:
                if o in c['blue']:
                    result['right_blue'].append(o)
        result.update(c)
        result_data.append(result)

    contacts2 = {"l_id":lo.id,
                "link__code":lo.code,
                "logo": "【{a}】{b}".format(a=lo.lottery_publisher, b=lo.lottery_name),
                }
    return render(requests, "lottery/old.html",{"title_info":title_info,
                            "contacts":result_data,"contacts2":contacts2})


def donate(requests):
    return render(requests, 'lottery/donate.html',{'title_info':"客官,可还满意?"})

def ai(requests):
    a_id_str = requests.GET.get("id")
    if a_id_str == '':
        a_id_list = []
    else:
        a_id_list = a_id_str.split(',')
    if requests.GET.get("lucky"):
        arr_num = random.choice(range(1,11))
    else:
        arr_num = 3
    
    # random
    random_status = 0
    if int(requests.GET.get("random")) == 1:
        random_status = 1
        title = "随机选号"
    else:
        title = "AI智能选号"
    f = int(requests.GET.get("l_id"))
    g = Open_history.objects.get(pk=f)
    contacts = {"code":g.code+1,
                "lottery_name":g.lottery_name,
                "lottery_publisher":g.lottery_publisher,
                "id":a_id_str,
                "l_id":f,
                "random":requests.GET.get("random")
                }

    red_list = []
    blue_list = []
    orange_list = []
    solida_list = []
    for a_id in a_id_list:
        d = Alg_everyone.objects.get(pk=int(a_id))
        json_data = json.loads(d.alg_data)
        if g.lottery_id in [3,4,5,6]:
            red_list.extend(json_data['will']['red'])
        elif g.lottery_id in [1,7]:
            red_list.extend(json_data['will']['red'])
            blue_list.extend(json_data['will']['blue'])
        elif g.lottery_id in [2]:
            orange_list.extend(json_data['will']['orange'])
            solida_list.extend(json_data['will']['solida'])

    red_list = list(set(red_list))
    blue_list = list(set(blue_list))
    orange_list = list(set(orange_list))
    solida_list = list(set(solida_list))

    contacts['lucky'] = []
    if g.lottery_id == 1:
        # 双色球
        for num_id in range(1,arr_num+1):
            lottery = {"num":num_id}
            if len(red_list) < 6 or random_status == 1:
                cc = random.sample(range(1,34), 6)
                cc.sort()
                lottery['red_list'] = cc
            else:
                cc = random.sample(red_list, 6)
                cc.sort()
                lottery['red_list'] = cc
            if len(blue_list) < 1 or random_status == 1:
                cc = random.sample(range(1,17), 1)
                cc.sort()
                lottery['blue_list'] = cc
            else:
                cc = random.sample(blue_list, 1)
                cc.sort()
                lottery['blue_list'] = cc
            contacts['lucky'].append(lottery)
    elif g.lottery_id == 2:
        # 大乐透
        for num_id in range(1,arr_num+1):
            lottery = {"num":num_id}
            if len(red_list) < 5 or random_status == 1:
                cc = random.sample(range(1,36), 5)
                cc.sort()
                lottery['orange_list'] = cc
            else:
                cc = random.sample(orange_list, 5)
                cc.sort()
                lottery['orange_list'] = cc
            if len(blue_list) < 2 or random_status == 1:
                cc = random.sample(range(1,13), 2)
                cc.sort()
                lottery['solida_list'] = cc
            else:
                cc = random.sample(solida_list, 2)
                cc.sort()
                lottery['solida_list'] = cc
            contacts['lucky'].append(lottery)
    elif g.lottery_id == 3:
        # 3D
        for num_id in range(1,arr_num+1):
            lottery = {"num":num_id}
            if random_status == 1:
                # 可以重复
                cc = [random.choice(range(10)) for _ in range(3)]
                lottery['red_list'] = cc
            else:
                # 可以重复
                cc = [random.choice(red_list) for _ in range(3)]
                lottery['red_list'] = cc
            contacts['lucky'].append(lottery)
    elif g.lottery_id == 4:
        # 七星彩
        for num_id in range(1,arr_num+1):
            lottery = {"num":num_id}
            if random_status == 1:
                # 可以重复
                cc = [random.choice(range(10)) for _ in range(7)]
                lottery['red_list'] = cc
            else:
                # 可以重复
                cc = [random.choice(red_list) for _ in range(7)]
                lottery['red_list'] = cc
            contacts['lucky'].append(lottery)
    elif g.lottery_id == 5:
        # 排列3
        for num_id in range(1,arr_num+1):
            lottery = {"num":num_id}
            if random_status == 1:
                # 可以重复
                cc = [random.choice(range(10)) for _ in range(3)]
                lottery['red_list'] = cc
            else:
                # 可以重复
                cc = [random.choice(red_list) for _ in range(3)]
                lottery['red_list'] = cc
            contacts['lucky'].append(lottery)
    elif g.lottery_id == 6:
        # 排列5
        for num_id in range(1,arr_num+1):
            lottery = {"num":num_id}
            if random_status == 1:
                # 可以重复
                cc = [random.choice(range(10)) for _ in range(5)]
                lottery['red_list'] = cc
            else:
                # 可以重复
                cc = [random.choice(red_list) for _ in range(5)]
                lottery['red_list'] = cc
            contacts['lucky'].append(lottery)
    elif g.lottery_id == 7:
        # 七乐彩
        for num_id in range(1,arr_num+1):
            lottery = {"num":num_id}
            if len(red_list) < 6 or random_status == 1:
                cc = random.sample(range(1,31), 6)
                cc.sort()
                lottery['red_list'] = cc
            else:
                cc = random.sample(red_list, 6)
                cc.sort()
                lottery['red_list'] = cc

            exclude_red = []
            for r in range(1,31):
                if r not in lottery['red_list']:
                    exclude_red.append(r)

            if len(blue_list) < 1 or random_status == 1:
                cc = random.sample(exclude_red, 1)
                cc.sort()
                lottery['blue_list'] = cc
            else:
                cc = random.sample(blue_list, 1)
                cc.sort()
                lottery['blue_list'] = cc
            
            contacts['lucky'].append(lottery)
     # 随机的时候，隐藏再来一次
    if random_status == 1:
        contacts["random_hidden"] = True
    return render(requests, 'lottery/ai.html',{'title_info':title,
                "contacts":contacts})